package com.lly.songhigh.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.activity.PlayMusicActivity;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.AlbumPic;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.receiver.MyReceiver;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 李新伟 on 15/10/28.
 */
public class MediaPlayerService extends Service {
    private MediaPlayer mediaPlayer;
    private List<MusicInfo> musicInfos;
    private int position;
    private String url;
    private MusicInfo musicInfo;
    private int recycleState;
    private RemoteViews remoteViews;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private static final String TAG = "MediaPlayerService";

    private void showView(String songName, String singerName) {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        remoteViews = new RemoteViews(getPackageName(), R.layout.music_notification);

        remoteViews.setTextViewText(R.id.songName, songName);
        remoteViews.setTextViewText(R.id.singerName, singerName);
        remoteViews.setImageViewResource(R.id.songer_pic, R.mipmap.music_songhigh);
        long albumId = musicInfos.get(position).getAlbumId();
        if (albumId != 0) {
            String url = URL.ALBUM_PIC_START + albumId+ URL.ALBUM_PIC_END;
            StringRequestUtf stringRequestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    AlbumPic albumPic = gson.fromJson(response, AlbumPic.class);
                    String picUrl = albumPic.getData().getPicUrl();
                    Picasso.with(MediaPlayerService.this).load(picUrl).into(remoteViews, R.id.songer_pic,
                            1, builder.build());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            VolleySingleton.getInstance().addQueue(stringRequestUtf);
        }

        // 设置按钮事件 -- 发送广播 --广播接收后进行对应的处理
        Intent buttonPlayIntent = new Intent(
                MyReceiver.NOTIFICATION_ITEM_BUTTON_LAST); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.last_music,
                pendButtonPlayIntent);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent1 = new Intent(
                MyReceiver.NOTIFICATION_ITEM_BUTTON_PLAY); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent1 = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.paly_pause_music,
                pendButtonPlayIntent1);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent2 = new Intent(
                MyReceiver.NOTIFICATION_ITEM_BUTTON_NEXT); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent2 = PendingIntent.getBroadcast(this,
                0, buttonPlayIntent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.next_music,
                pendButtonPlayIntent2);// ----设置对应的按钮ID监控

        Intent buttonDeleteIntent = new Intent(
                MyReceiver.NOTIFICATION_ITEM_BUTTON_DELETE); // ----设置通知栏清除按钮
        PendingIntent pendButtonDeleteIntent = PendingIntent.getBroadcast(this,
                0, buttonDeleteIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.delete_notification,
                pendButtonDeleteIntent);// ----设置对应的按钮ID监控

        Intent intentToActivity = new Intent(this, PlayMusicActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 100, intentToActivity, PendingIntent.FLAG_UPDATE_CURRENT);
        builder = new NotificationCompat.Builder(this);
        builder.setContent(remoteViews).setSmallIcon(R.mipmap.notification_ticker)
                .setOngoing(true).setTicker(songName);
        builder.setContentIntent(pi);
        manager.notify(1, builder.build());

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MediaBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // 设置音频流
        /**
         * 播放完成监听
         */
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.reset();
                EventBus.getDefault().post(new MyEvent.PlayControl(8));
            }
        });
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "退出服务");
        stopSelf();
        // 释放资源
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        EventBus.getDefault().unregister(this);
        if (manager != null) {
            manager.cancel(1);
        }
    }


    public class MediaBinder extends Binder {

        public int getCurrentPosition() {
            return mediaPlayer.getCurrentPosition();
        }

        // 改变播放进度
        public void seekTo(int index) {
            mediaPlayer.seekTo(index);
        }

        // 获得音乐时长
        public int getMax() {
            return mediaPlayer.getDuration();
        }

        // 获取歌手名
        public String getSingerName() {
            return musicInfo.getSingerName();
        }

        // 获取歌曲名
        public String getSongName() {
            return musicInfo.getSongName();
        }

        // 获取歌手ID
        public long getSingerId() {
            return musicInfo.getSingerId();
        }

        // 获取歌曲ID
        public long getSongId() {
            return musicInfo.getSongId();
        }

        // 获取音乐集合
        public List<MusicInfo> getMusicinfos() {
            return musicInfos;
        }

        // 获取当前播放位置
        public int getPosition() {
            return position;
        }

        // 获取歌曲来源
        public String getResouce() {
            return musicInfo.getResouce();
        }

        // 获取当前播放音乐信息
        public MusicInfo getMusicInfo() {
            return musicInfo;
        }
    }


    public void play() {
        musicInfo = musicInfos.get(position);
        url = musicInfos.get(position).getUrl();
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onEvent(MyEvent.RecycleMode recycleMode) {
        recycleState = recycleMode.getPlayMode();
    }

    public void onEvent(MyEvent.CleanNotification cleanNotification) {
        if (cleanNotification.isClean()) {
            if (!mediaPlayer.isPlaying()) {
                Log.i(TAG, "清除通知栏");
                manager.cancel(1);
            }
        }
    }

    public void onEvent(MyEvent.OpenMusic openMusic) {
        if (openMusic.isOpen()) {
            Log.i(TAG, "打开Activity界面");
            showView(musicInfos.get(position).getSongName(), musicInfos.get(position).getSingerName());
            EventBus.getDefault().post(new MyEvent.RefreshUI(mediaPlayer != null));
        }
    }

    public void onEvent(MyEvent.ChangeIcon changeIcon) {
        switch (changeIcon.getI()) {
            case 1:
                Log.i(TAG, "暂停");
                remoteViews.setImageViewResource(R.id.paly_pause_music, R.mipmap.play_icn_src_prs);
                manager.notify(1, builder.build());
                break;
        }
    }

    public void onEvent(MyEvent.PlayControl playControl) {
        switch (playControl.getWhat()) {
            case 6: // 下一首
                if (recycleState == 0) { // 全部循环
                    if (position == musicInfos.size() - 1)
                        position = 0;
                    else
                        position++;
                }
                if (recycleState == 1) { // 随机播放
                    position = new Random().nextInt(musicInfos.size() - 1);
                }
                if (recycleState == 2) { // 单曲循环
                    if (position == musicInfos.size() - 1)
                        position = 0;
                    else
                        position++;
                }
                play();
                break;
            case 7: //上一首
                if (recycleState == 0) { // 全部循环
                    if (position == 0)
                        position = musicInfos.size() - 1;
                    else
                        position--;
                }
                if (recycleState == 1) { // 随机播放
                    position = new Random().nextInt(musicInfos.size() - 1);
                }
                if (recycleState == 2) { // 单曲循环
                    if (position == 0)
                        position = musicInfos.size() - 1;
                    else
                        position--;
                }
                play();
                break;
            case 8: // 自动播放下一首
                if (recycleState == 0) { // 全部循环
                    if (position == musicInfos.size() - 1)
                        position = 0;
                    else
                        position++;
                }
                if (recycleState == 1) { // 随机播放
                    position = new Random().nextInt(musicInfos.size() - 1);
                }
                if (recycleState == 2) { // 单曲循环
                }
                play();
                break;
        }
        showView(musicInfos.get(position).getSongName(), musicInfos.get(position).getSingerName());
    }

    // 接收传递过来的数据
    public void onEvent(MyEvent.DeliverData deliverData) {
        musicInfos = deliverData.getMusicInfos();
        String songName = deliverData.getSongName();
        for (int i = 0; i < musicInfos.size(); i++) {
            if (musicInfos.get(i).getSongName().equals(songName)) {
                position = i;
                break;
            }
        }
        play();
        showView(musicInfos.get(position).getSongName(), musicInfos.get(position).getSingerName());
    }

    public void onEvent(MyEvent.MediaPlay mediaPlay) {
        switch (mediaPlay.getWhat()) {
            case 1:
                play();
                break;
            case 2: // 暂停
                remoteViews.setImageViewResource(R.id.paly_pause_music, R.mipmap.music_play);
                manager.notify(1, builder.build());
                mediaPlayer.pause();
                break;
            case 3: // 播放
                remoteViews.setImageViewResource(R.id.paly_pause_music, R.mipmap.music_pause);
                manager.notify(1, builder.build());
                mediaPlayer.start();
                break;
        }
    }

    // 点击音乐播放列表会接收到的方法
    public void onEvent(MyEvent.PlayMusicList playMusicList) {
        position = playMusicList.getPosition();
        play();
    }
}
